package org.jeeasy.system.modules.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeeasy.common.core.annotation.auth.AuthType;
import org.jeeasy.common.core.config.constant.CommonConstant;
import org.jeeasy.common.core.domain.IAuthUser;
import org.jeeasy.common.core.domain.Permission;
import org.jeeasy.common.core.exception.JeeasyException;
import org.jeeasy.common.core.service.IAuthService;
import org.jeeasy.common.core.tools.Tools;
import org.jeeasy.system.modules.premission.domain.SysPermission;
import org.jeeasy.system.modules.premission.service.SysPermissionService;
import org.jeeasy.system.modules.user.domain.SysUser;
import org.jeeasy.system.modules.user.domain.model.SystemAuthUser;
import org.jeeasy.system.modules.user.service.SysUserService;
import org.jeeasy.system.property.SystemConfigProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统用户登录认证服务接口
 *
 * @author Alps
 */
@Slf4j
@Component("systemAuthService")
@AuthType(type = AuthType.Type.SYS_USER, izDefault = true)
@EnableConfigurationProperties(SystemConfigProperties.class)
@RequiredArgsConstructor
public class SystemAuthServiceImpl implements IAuthService<SystemAuthUser> {

    private final SysUserService sysUserService;

    private final SysPermissionService permissionService;

    //@Lazy
    //@Resource
    //private SystemAuthServiceImpl authService;

    @Override
    @Cacheable(value = CommonConstant.CACHE_SYS_USER_KEY, key = "#username")
    public SystemAuthUser getAuthUserByUsername(String username) {
        SysUser sysUser = sysUserService.getByUserName(username);
        if (Tools.isNotEmpty(sysUser)) {
            SystemAuthUser authUser = IAuthUser.create(sysUser, SystemAuthUser.class);
            authUser.setPermissionSet(this.getPermissionSetByUsername(username)).setRoleSet(this.getRoleSetByUsername(username));
            return authUser;
//            return IAuthUser.create(sysUser, SystemAuthUser.class);
        }
        return null;
    }

    @Override
//    @CacheEvict(value = CommonConstant.CACHE_SYS_USER_KEY, key = "#username")
    public SystemAuthUser login(String username, String password) {
        if (sysUserService.checkPasswordByUserName(username, password)) {
            return getAuthUserByUsername(username);
        } else {
            throw new JeeasyException("用户名或密码不正确");
        }

//        try {
//            // 验证码
//            if (properties.getEnableCaptcha()) {
//                String captcha = ServletUtil.getRequest().getParameter("captcha");
//                String captchaKey = ServletUtil.getRequest().getParameter("captchaKey");
//                Tools.verifyCaptcha(captchaKey, captcha);
//            }
//        } catch (JeeasyException e) {
//            throw new BadCredentialsException(e.getMessage());
//        }
//
//        String password = (String) authentication.getCredentials();
//        SysUser sysUser = sysUserService.getByUserName(username);
//
//        if (Tools.isEmpty(sysUser)) {
//            throw new UsernameNotFoundException("用户名不存在");
//        }
//        if (SysUserUtil.create(sysUser).checkPassword(password)) {
////            SystemAuthUser authUser = IAuthUser.create(sysUser, SystemAuthUser.class);
////            authUser.setPermissions(this.getPermissionSetByUsername(username)).setRoles(this.getRoleSetByUsername(username));
////            return authUser;
//            return true;
//        } else {
//            throw new BadCredentialsException("密码错误");
//        }
//         return null;
    }

    @Override
    public Set<String> getRoleSetByUsername(String username) {
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        return roles;
    }

    @Override
    public Set<String> getPermissionSetByUsername(String username) {
        Set<String> pset = new HashSet<>();
        SysUser user = sysUserService.getByUserName(username);
        if (Tools.isNotEmpty(user)) {
            List<SysPermission> userPermissions = null;
            if (IAuthUser.SUPER_USERNAME.equals(username)) {
                userPermissions = permissionService.queryAll();
            } else {
                userPermissions = permissionService.queryByUserId(user.getId());
            }
            userPermissions.forEach(p -> {
                pset.add(p.getPerms());
            });
        }
        return pset;
    }

    @Override
    public Set<Permission> getAllPermission() {
        return new HashSet<>();
    }

    @Override
    public void onAuthenticationSuccess(IAuthUser authUser) {
        log.info("用户[ {} ]登录成功", authUser.username());
        StpUtil.getSession().set(IAuthService.SESSION_USER_KEY, authUser);
    }

}
